import { useEffect, useMemo } from 'react'
import { useMemoizedFn } from 'ahooks'
import { Modal, Space } from 'antd'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { useAntdPopupAnimation } from '@/services/popupSlot'
import { addAGCellTexty } from '@oBiz/components/addTexty'
import { IInpTransferOrderNumItem, TCellParams, TCol } from './interface'
import { useBoundStore } from './store'
import { createInitialData, isEmptyRow } from './utils'
import countFailImg from '@/assets/countFail.svg'
import countSuccessImg from '@/assets/countSuccess.svg'
import countTotalImg from '@/assets/countTotal.svg'
import styles from './styles.module.less'

interface InpTransferOrderNumModalProps {
  destroy: () => void
  onSuccess?: () => void
}

const Cell = (p: TCellParams) => {
  return addAGCellTexty(p)
}

/** 录入转单号弹窗 */
export const InpTransferOrderNumModal = ({ destroy, onSuccess }: InpTransferOrderNumModalProps) => {
  const { open, onHide, afterOpenChange } = useAntdPopupAnimation(destroy)

  const gridRef = useBoundStore(v => v.gridRef)
  const data = useBoundStore(v => v.data)
  const isValid = useBoundStore(v => v.isValid)
  const submitting = useBoundStore(v => v.submitting)
  const hasSucceeded = useBoundStore(v => v.hasSucceeded)
  const currentCountInfo = useBoundStore(v => v.currentCountInfo)
  const setData = useBoundStore(v => v.setData)
  const validate = useBoundStore(v => v.validate)
  const handleSubmit = useBoundStore(v => v.handleSubmit)

  // 列配置
  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      flex: 1,
      minWidth: 180,
      sortable: false,
      mainMenuItems: ['autoSizeThis', 'autoSizeAll', 'separator', 'resetColumns'],
      editable: true,
      cellRenderer: Cell,
      cellClassRules: {
        [styles.is_error]: ({ colDef, value, data }) => {
          if (!colDef.editable) return false
          return !value && !isEmptyRow(data)
        },
        [styles.is_readonly]: ({ colDef }) => !colDef.editable,
        [styles.is_result_error]: ({ data, colDef }) => colDef.field === 'message' && !!data?.message,
      },
    }),
    [],
  )
  const columnDefs = useMemo(
    () => [
      {
        field: '序号',
        flex: 0.01,
        minWidth: 62,
        editable: false,
        resizable: false,
        mainMenuItems: [],
        suppressHeaderMenuButton: true,
        valueFormatter: ({ node }) => `${node ? node.childIndex + 1 : ''}`,
      } satisfies TCol<'序号'>,
      {
        field: 'waybillNo',
        headerName: '运单编号',
      } satisfies TCol<'waybillNo'>,
      {
        field: 'trackingNumber',
        headerName: '转单号',
      } satisfies TCol<'trackingNumber'>,
      {
        field: 'logisticsCompany',
        headerName: '物流公司',
      } satisfies TCol<'logisticsCompany'>,
      {
        field: 'message',
        headerName: '识别结果',
        editable: false,
        flex: 0.01,
        minWidth: 114 + 20,
      } satisfies TCol<'message'>,
    ],
    [],
  )

  // 拖动填充
  const cellSelection = useMemo<ICusAgGridProps['cellSelection']>(
    () => ({
      handle: {
        mode: 'fill',
        direction: 'y',
        suppressClearOnFillReduction: true,
      },
    }),
    [],
  )

  // 值变更
  const onCellValueChanged = useMemoizedFn<NonNullable<ICusAgGridProps['onCellValueChanged']>>(
    ({ colDef, newValue, oldValue, node, data }) => {
      if (!colDef.field) return
      oldValue = oldValue?.trim() || '' // oldValue 可能为 null
      newValue = newValue?.trim() || '' // newValue 可能为 null
      node.setData({
        ...data,
        [colDef.field]: newValue,
        ...(newValue !== oldValue ? { message: null } : {}),
      })
      validate() // 触发校验
    },
  )

  // 触发校验
  useEffect(() => validate(), [data, validate])

  // 初始空行
  useEffect(() => setData(createInitialData()), [setData])

  // 清理
  useEffect(() => () => useBoundStore.setState(useBoundStore.getInitialState(), true), [])

  return (
    <Modal
      title="录入转单号"
      width={1200}
      open={open}
      onCancel={() => {
        onHide()
        if (hasSucceeded) onSuccess?.()
      }}
      afterOpenChange={afterOpenChange}
      okButtonProps={{ disabled: !isValid, loading: submitting }}
      okText="提交"
      onOk={handleSubmit}
      footer={(_originNode, { OkBtn, CancelBtn }) => (
        <div className={styles.footer}>
          <Space size={20}>
            <span>本次录入结果：</span>
            <Space size={4}>
              <img src={countTotalImg} />
              <span>录入总数</span>
              <b>{currentCountInfo?.totalNum ?? '--'}</b>
            </Space>
            <Space size={4}>
              <img src={countSuccessImg} />
              <span>录入成功</span>
              <b>{currentCountInfo?.successNum ?? '--'}</b>
            </Space>
            <Space size={4}>
              <img src={countFailImg} />
              <span>录入失败</span>
              <b>{currentCountInfo?.failNum ?? '--'}</b>
            </Space>
          </Space>
          <Space>
            <CancelBtn />
            <OkBtn />
          </Space>
        </div>
      )}
    >
      <div style={{ height: 600 }}>
        <CusAgGrid<IInpTransferOrderNumItem>
          ref={gridRef}
          rowData={data}
          loading={submitting}
          getRowId={undefined}
          defaultColDef={defaultColDef}
          columnDefs={columnDefs}
          suppressMovableColumns
          undoRedoCellEditing
          cellSelection={cellSelection}
          onCellValueChanged={onCellValueChanged}
        />
      </div>
    </Modal>
  )
}
